﻿
using System;
using System.Linq;
using System.Reflection;

namespace mediaPrime.TVServerProvider
{
    public class TVServerProviderManager
    {
        public static TVServerProviderBase LoadTVServerProvider(string path)
        {
            if (!System.IO.File.Exists(path))
            {
                return null;
            }

            try
            {
                // Load Assembly
                Assembly assembly = Assembly.LoadFrom(path);
                if (assembly != null)
                {
                    // Search for PluginAttribute to get Plugin class
                    var attribute = assembly.GetCustomAttributes(typeof(TVServerProviderAttribute), true).FirstOrDefault() as TVServerProviderAttribute;
                    if (attribute != null)
                    {
                        var type = assembly.GetTypes().SingleOrDefault(t => t.Name == attribute.ClassName);

                        if (typeof(TVServerProviderBase).IsAssignableFrom(type))
                        {
                            var plugin = Activator.CreateInstance(type) as TVServerProviderBase;
                            if (plugin != null) // Found!  
                            {
                                return plugin;
                            }
                        }

                    }
                }
            }
            catch (Exception ex)
            {

            }

            return null;
        }
    }
}
